/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.dao;

import static cn.itlaobing.util.IConstants.DRIVER;
import static cn.itlaobing.util.IConstants.PWD;
import static cn.itlaobing.util.IConstants.URL;
import static cn.itlaobing.util.IConstants.USER;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.itlaobing.util.IRowMapper;

/** 
 * ClassName: DBHelper <br/> 
 * Function: dbhelper类<br/> 
 * date: 2017年11月1日 下午2:33:19 <br/> 
 * 
 * @author wd
 * @version @param <T> 
 * @since JDK 1.8 
 */
public class DBHelper<T> {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//获得连接
	public void openConnection()throws ClassNotFoundException,SQLException{
		if(conn==null || conn.isClosed()) {
			conn=DriverManager.getConnection(URL,USER,PWD);
		}
	}
	//关闭连接
	public void close()throws SQLException{
		if(rs!=null)rs.close();
		if(ps!=null)ps.close();
		if(conn!=null)conn.close();
	}
	//设置参数
	private void setParameters(Object ... params)throws SQLException{
		if(params!=null && params.length>0) {
			for(int i=0;i<params.length;i++) {
				ps.setObject(i+1, params[i]);
			}
		}
	}
	//查询方法
	public ResultSet executeQuery(String sql,Object...params)throws ClassNotFoundException,SQLException{
		
		openConnection();
	
		ps=conn.prepareStatement(sql);
	
		setParameters(params);
		
		rs=ps.executeQuery();
		return rs;
	}
	//修改方法
	public int executeUpdate(String sql,Object...params)throws ClassNotFoundException,SQLException{
		openConnection();
		ps=conn.prepareStatement(sql);
		setParameters(params);
		return ps.executeUpdate();
	}


	public List<T> executeQueryHelper(IRowMapper<T> rowMapper, String sql,Object...params)throws SQLException,ClassNotFoundException{
		List<T> list=new ArrayList<T>();
		rs=executeQuery(sql, params);
		while(rs.next()) {
			T t=rowMapper.mapper(rs);
			list.add(t);
		}
		return list;
	}
}
